/*!
 * \file python_binding.cpp
 * \project AI_CTP
 * 
 * \brief PyBind11绑定实现 - 基于wt_ctp成功实现
 */

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/functional.h>
#include <pybind11/chrono.h>
#include <memory>

#include "include/md_api.hpp"
#include "include/trader_api.hpp"

namespace py = pybind11;
using namespace ctp_api;

// Python行情回调包装类
class PyMdCallback : public IMdCallback {
public:
    PyMdCallback() = default;
    virtual ~PyMdCallback() = default;

    // 连接事件
    void on_connected() override {
        PYBIND11_OVERLOAD(void, IMdCallback, on_connected, );
    }

    void on_disconnected(int reason) override {
        PYBIND11_OVERLOAD(void, IMdCallback, on_disconnected, reason);
    }

    // 登录事件
    void on_login_success() override {
        PYBIND11_OVERLOAD(void, IMdCallback, on_login_success, );
    }

    void on_login_failed(int error_id, const std::string& error_msg) override {
        PYBIND11_OVERLOAD(void, IMdCallback, on_login_failed, error_id, error_msg);
    }

    // 数据事件
    void on_tick(const TickInfo& tick) override {
        PYBIND11_OVERLOAD(void, IMdCallback, on_tick, tick);
    }

    void on_kline(const BarInfo& bar) override {
        PYBIND11_OVERLOAD(void, IMdCallback, on_kline, bar);
    }

    // 错误事件
    void on_error(int error_id, const std::string& error_msg) override {
        PYBIND11_OVERLOAD(void, IMdCallback, on_error, error_id, error_msg);
    }
};

// Python交易回调包装类
class PyTraderCallback : public ITraderCallback {
public:
    using ITraderCallback::ITraderCallback;

    void on_connected() override {
        PYBIND11_OVERLOAD(void, ITraderCallback, on_connected);
    }

    void on_disconnected(int reason) override {
        PYBIND11_OVERLOAD(void, ITraderCallback, on_disconnected, reason);
    }

    void on_login_success() override {
        PYBIND11_OVERLOAD(void, ITraderCallback, on_login_success);
    }

    void on_login_failed(const std::string& error_msg) override {
        PYBIND11_OVERLOAD(void, ITraderCallback, on_login_failed, error_msg);
    }

    void on_order_insert(const OrderInfo& order) override {
        PYBIND11_OVERLOAD(void, ITraderCallback, on_order_insert, order);
    }

    void on_order_update(const OrderInfo& order) override {
        PYBIND11_OVERLOAD(void, ITraderCallback, on_order_update, order);
    }

    void on_order_error(const std::string& error_msg) override {
        PYBIND11_OVERLOAD(void, ITraderCallback, on_order_error, error_msg);
    }

    void on_trade(const TradeInfo& trade) override {
        PYBIND11_OVERLOAD(void, ITraderCallback, on_trade, trade);
    }

    void on_account_info(const AccountInfo& account) override {
        PYBIND11_OVERLOAD(void, ITraderCallback, on_account_info, account);
    }

    void on_position_info(const PositionInfo& position) override {
        PYBIND11_OVERLOAD(void, ITraderCallback, on_position_info, position);
    }

    void on_error(int error_code, const std::string& error_msg) override {
        PYBIND11_OVERLOAD(void, ITraderCallback, on_error, error_code, error_msg);
    }
};

PYBIND11_MODULE(ai_ctp, m) {
    m.doc() = "AI-CTP: High-performance CTP wrapper for Python - Based on wt_ctp success implementation";
    m.attr("__version__") = "1.0.0-enterprise";
    m.attr("__build_type__") = "Enterprise";
    m.attr("__author__") = "量化工程师团队";
    m.attr("__description__") = "企业级高性能CTP期货接口";

    // 状态枚举
    py::enum_<MdState>(m, "MdState")
        .value("DISCONNECTED", MdState::DISCONNECTED)
        .value("CONNECTING", MdState::CONNECTING)
        .value("CONNECTED", MdState::CONNECTED)
        .value("LOGGING_IN", MdState::LOGGING_IN)
        .value("LOGGED_IN", MdState::LOGGED_IN)
        .value("READY", MdState::READY)
        .export_values();

    py::enum_<TradeState>(m, "TradeState")
        .value("DISCONNECTED", TradeState::DISCONNECTED)
        .value("CONNECTING", TradeState::CONNECTING)
        .value("CONNECTED", TradeState::CONNECTED)
        .value("AUTHENTICATING", TradeState::AUTHENTICATING)
        .value("AUTHENTICATED", TradeState::AUTHENTICATED)
        .value("LOGGING_IN", TradeState::LOGGING_IN)
        .value("LOGGED_IN", TradeState::LOGGED_IN)
        .value("CONFIRMING", TradeState::CONFIRMING)
        .value("CONFIRMED", TradeState::CONFIRMED)
        .value("READY", TradeState::READY);

    // Tick数据结构
    py::class_<TickInfo>(m, "TickInfo")
        .def(py::init<>())
        .def_readwrite("instrument_id", &TickInfo::instrument_id)
        .def_readwrite("trading_day", &TickInfo::trading_day)
        .def_readwrite("update_time", &TickInfo::update_time)
        .def_readwrite("action_day", &TickInfo::action_day)
        .def_readwrite("last_price", &TickInfo::last_price)
        .def_readwrite("volume", &TickInfo::volume)
        .def_readwrite("turnover", &TickInfo::turnover)
        .def_readwrite("open_interest", &TickInfo::open_interest)
        .def_readwrite("bid_price1", &TickInfo::bid_price1)
        .def_readwrite("bid_volume1", &TickInfo::bid_volume1)
        .def_readwrite("ask_price1", &TickInfo::ask_price1)
        .def_readwrite("ask_volume1", &TickInfo::ask_volume1)
        .def_readwrite("open_price", &TickInfo::open_price)
        .def_readwrite("high_price", &TickInfo::high_price)
        .def_readwrite("low_price", &TickInfo::low_price)
        .def_readwrite("pre_close_price", &TickInfo::pre_close_price)
        .def_readwrite("upper_limit_price", &TickInfo::upper_limit_price)
        .def_readwrite("lower_limit_price", &TickInfo::lower_limit_price);

    // K线数据结构
    py::class_<BarInfo>(m, "BarInfo")
        .def(py::init<>())
        .def_readwrite("instrument_id", &BarInfo::instrument_id)
        .def_readwrite("time_str", &BarInfo::time_str)
        .def_readwrite("bar_time", &BarInfo::bar_time)
        .def_readwrite("period", &BarInfo::period)
        .def_readwrite("open", &BarInfo::open)
        .def_readwrite("high", &BarInfo::high)
        .def_readwrite("low", &BarInfo::low)
        .def_readwrite("close", &BarInfo::close)
        .def_readwrite("volume", &BarInfo::volume)
        .def_readwrite("turnover", &BarInfo::turnover)
        .def_readwrite("open_interest", &BarInfo::open_interest);

    // 订单信息结构
    py::class_<OrderInfo>(m, "OrderInfo")
        .def(py::init<>())
        .def_readwrite("instrument_id", &OrderInfo::instrument_id)
        .def_readwrite("order_ref", &OrderInfo::order_ref)
        .def_readwrite("order_sys_id", &OrderInfo::order_sys_id)
        .def_readwrite("direction", &OrderInfo::direction)
        .def_readwrite("offset_flag", &OrderInfo::offset_flag)
        .def_readwrite("limit_price", &OrderInfo::limit_price)
        .def_readwrite("volume_total_original", &OrderInfo::volume_total_original)
        .def_readwrite("volume_traded", &OrderInfo::volume_traded)
        .def_readwrite("volume_left", &OrderInfo::volume_left)
        .def_readwrite("order_status", &OrderInfo::order_status)
        .def_readwrite("status_msg", &OrderInfo::status_msg)
        .def_readwrite("insert_time", &OrderInfo::insert_time)
        .def_readwrite("update_time", &OrderInfo::update_time)
        .def_readwrite("front_id", &OrderInfo::front_id)
        .def_readwrite("session_id", &OrderInfo::session_id);

    // 成交信息结构
    py::class_<TradeInfo>(m, "TradeInfo")
        .def(py::init<>())
        .def_readwrite("trade_id", &TradeInfo::trade_id)
        .def_readwrite("order_ref", &TradeInfo::order_ref)
        .def_readwrite("order_sys_id", &TradeInfo::order_sys_id)
        .def_readwrite("instrument_id", &TradeInfo::instrument_id)
        .def_readwrite("direction", &TradeInfo::direction)
        .def_readwrite("offset_flag", &TradeInfo::offset_flag)
        .def_readwrite("price", &TradeInfo::price)
        .def_readwrite("volume", &TradeInfo::volume)
        .def_readwrite("trade_time", &TradeInfo::trade_time);

    // 持仓信息结构
    py::class_<PositionInfo>(m, "PositionInfo")
        .def(py::init<>())
        .def_readwrite("instrument_id", &PositionInfo::instrument_id)
        .def_readwrite("pos_direction", &PositionInfo::pos_direction)
        .def_readwrite("position", &PositionInfo::position)
        .def_readwrite("position_today", &PositionInfo::position_today)
        .def_readwrite("position_yesterday", &PositionInfo::position_yesterday)
        .def_readwrite("open_cost", &PositionInfo::open_cost)
        .def_readwrite("position_cost", &PositionInfo::position_cost)
        .def_readwrite("margin", &PositionInfo::margin)
        .def_readwrite("profit", &PositionInfo::profit);

    // 账户信息结构
    py::class_<AccountInfo>(m, "AccountInfo")
        .def(py::init<>())
        .def_readwrite("account_id", &AccountInfo::account_id)
        .def_readwrite("pre_balance", &AccountInfo::pre_balance)
        .def_readwrite("balance", &AccountInfo::balance)
        .def_readwrite("available", &AccountInfo::available)
        .def_readwrite("margin", &AccountInfo::margin)
        .def_readwrite("profit", &AccountInfo::profit)
        .def_readwrite("commission", &AccountInfo::commission);

    // 订单请求结构
    py::class_<OrderRequest>(m, "OrderRequest")
        .def(py::init<>())
        .def_readwrite("instrument_id", &OrderRequest::instrument_id)
        .def_readwrite("direction", &OrderRequest::direction)
        .def_readwrite("offset_flag", &OrderRequest::offset_flag)
        .def_readwrite("limit_price", &OrderRequest::limit_price)
        .def_readwrite("volume", &OrderRequest::volume)
        .def_readwrite("price_type", &OrderRequest::price_type)
        .def_readwrite("time_condition", &OrderRequest::time_condition);

    // 撤单请求结构
    py::class_<CancelRequest>(m, "CancelRequest")
        .def(py::init<>())
        .def_readwrite("order_ref", &CancelRequest::order_ref)
        .def_readwrite("order_sys_id", &CancelRequest::order_sys_id)
        .def_readwrite("front_id", &CancelRequest::front_id)
        .def_readwrite("session_id", &CancelRequest::session_id);

    // 错误信息结构
    py::class_<ErrorInfo>(m, "ErrorInfo")
        .def(py::init<>())
        .def(py::init<int, const std::string&>())
        .def_readwrite("error_id", &ErrorInfo::error_id)
        .def_readwrite("error_msg", &ErrorInfo::error_msg)
        .def("is_error", &ErrorInfo::is_error);

    // 行情回调接口 - 使用shared_ptr作为holder类型
    py::class_<IMdCallback, PyMdCallback, std::shared_ptr<IMdCallback>>(m, "PyMdCallback")
        .def(py::init<>())
        .def("on_connected", &IMdCallback::on_connected)
        .def("on_disconnected", &IMdCallback::on_disconnected)
        .def("on_login_success", &IMdCallback::on_login_success)
        .def("on_login_failed", &IMdCallback::on_login_failed)
        .def("on_tick", &IMdCallback::on_tick)
        .def("on_kline", &IMdCallback::on_kline)
        .def("on_error", &IMdCallback::on_error);

    // 交易回调接口 - 使用shared_ptr作为holder类型
    py::class_<ITraderCallback, PyTraderCallback, std::shared_ptr<ITraderCallback>>(m, "PyTraderCallback")
        .def(py::init<>())
        .def("on_connected", &ITraderCallback::on_connected)
        .def("on_disconnected", &ITraderCallback::on_disconnected)
        .def("on_login_success", &ITraderCallback::on_login_success)
        .def("on_login_failed", &ITraderCallback::on_login_failed)
        .def("on_order_insert", &ITraderCallback::on_order_insert)
        .def("on_order_update", &ITraderCallback::on_order_update)
        .def("on_order_error", &ITraderCallback::on_order_error)
        .def("on_trade", &ITraderCallback::on_trade)
        .def("on_account_info", &ITraderCallback::on_account_info)
        .def("on_position_info", &ITraderCallback::on_position_info)
        .def("on_error", &ITraderCallback::on_error);

    // 行情API类
    py::class_<MdApi>(m, "MdApi")
        .def(py::init<>())
        .def("init", &MdApi::init)
        .def("start", &MdApi::start)
        .def("stop", &MdApi::stop)
        .def("is_connected", &MdApi::is_connected)
        .def("subscribe", &MdApi::subscribe)
        .def("unsubscribe", &MdApi::unsubscribe)
        .def("enable_kline", &MdApi::enable_kline)
        .def("disable_kline", &MdApi::disable_kline)
        .def("set_callback", [](MdApi& self, std::shared_ptr<IMdCallback> callback) {
            self.set_callback(callback);
        })
        .def("get_klines", &MdApi::get_klines);

    // 交易API类
    py::class_<TraderApi>(m, "TraderApi")
        .def(py::init<>())
        .def("init", &TraderApi::init)
        .def("release", &TraderApi::release)
        .def("connect", &TraderApi::connect)
        .def("disconnect", &TraderApi::disconnect)
        .def("is_connected", &TraderApi::is_connected)
        .def("login", &TraderApi::login)
        .def("logout", &TraderApi::logout)
        .def("insert_order", &TraderApi::insert_order)
        .def("cancel_order", &TraderApi::cancel_order)
        .def("query_account", &TraderApi::query_account)
        .def("query_positions", &TraderApi::query_positions)
        .def("query_orders", &TraderApi::query_orders)
        .def("query_trades", &TraderApi::query_trades)
        .def("set_callback", [](TraderApi& self, std::shared_ptr<ITraderCallback> callback) {
            self.set_callback(callback);
        });

    // 连接状态枚举 (基础版本)
    py::enum_<ConnectionState>(m, "ConnectionState")
        .value("DISCONNECTED", ConnectionState::DISCONNECTED)
        .value("CONNECTING", ConnectionState::CONNECTING)
        .value("CONNECTED", ConnectionState::CONNECTED)
        .value("LOGGED_IN", ConnectionState::LOGGED_IN)
        .value("READY", ConnectionState::READY)
        .export_values();

    // 基础版本信息
    m.attr("__version__") = "1.0.0-Enterprise";
    m.attr("__build_type__") = "Release";
    m.attr("__description__") = "AI_CTP Enterprise Edition - Professional Futures Trading Interface";
    
    // 注意：工厂模式功能将在后续版本中添加
    // 当前版本专注于核心API功能的稳定性
} 